<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/24 0024
 * Time: 下午 1:52
 */

namespace App\Http\Middleware;



use App\Models\Admin;
use App\Models\AssignedRoles;
use App\Models\Permissions;
use Illuminate\Support\Facades\Gate;
use Silber\Bouncer\Bouncer;
use Silber\Bouncer\Database\Role;

class CheckRoles
{
    public function handle($request, \Closure $next)
    {
        $uses =$request->route()->getActionName(); //实际访问的控制器和方法

        $actions = explode('\\',$uses);
        $controller = (explode('@',array_pop($actions)))[0];//获取当前访问的控制器

        $allow_controller = ['LoginController','TestController']; //不需要验证的控制器

        if (in_array($controller,$allow_controller)){
            return $next($request);
        }

        //获取用户的角色
        $admin_id = session('admin_info.id');
        $entity_ids = AssignedRoles::where(['entity_id'=>$admin_id])->pluck('role_id');
        if (collect($entity_ids)->isEmpty()){
            return back()->with(['msg'=>'该用户没有分配角色','status'=>1,'msg_url'=>'/admin/inex']);

        }

        $entity_ids = collect($entity_ids)->toArray();
        //判断是否有超级管理员权限
        if (in_array(1,$entity_ids)){
            return $next($request);
        }

//        //获取角色对应的权限
//        $list = Permissions::with('ability')->whereIn('entity_id',$entity_ids)->get();
//        foreach ($list as $item){
//            $roles[] = $item->ability->name;
//        }
//        if (!in_array($uses,$roles)){
//            return back()->with(['msg'=>'权限不足','status'=>1,'msg_url'=>'/admin/inex']);
//        }


        $bouncer = Bouncer::create(Admin::find($admin_id));
        if(!$bouncer->can($uses)){
            return back()->with(['msg'=>'权限不足','status'=>0,'msg_url'=>'/admin/index']);
        }

        return $next($request);
    }
}